package cn.com.git.example.config.manager;

import cn.com.git.example.common.util.security.CodecUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author zhangzhenfu
 * @Description
 * @date 2021/3/20 0020 9:31
 */
@Component
public class FileManager {
    @Value("${file.path}")
    private String fileLibPath;

    /**
     * 文件上传
     * @param is
     * @param targetFileName
     * @return
     */
    public String upload(InputStream is,String targetFileName){
        String dir = CodecUtils.get32UUID();
        String fileItemPath = dir + "/" + targetFileName;
        File file = new File((fileLibPath + "/" + fileItemPath)) ;
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        file.deleteOnExit();
        String result = null;
        try {
            file.createNewFile();
            FileUtils.copyInputStreamToFile(is,file);
            result = fileItemPath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 文件下载
     * @param response
     * @param fileItemPath
     */
    public void download(HttpServletResponse response, String fileItemPath){
        File file = new File((fileLibPath + "/" + fileItemPath)) ;
        if(!file.exists()){
            return;
        }
        String fileName = file.getName();
        InputStream is = null;
        OutputStream os = null;
        try{
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            is = new FileInputStream(file);
            os = response.getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
